import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { DataService } from '../../../services/data.service';
import { StepbarService } from './stepbar.service'
import * as _ from 'lodash'
import { PublicEventService } from '../public-event.service';
@Component({
  selector: 'app-stepbar',
  templateUrl: './stepbar.component.html',
  styleUrls: ['./stepbar.component.scss'],
  providers: [StepbarService]

})
export class PublicStepbarComponent implements OnInit {

  @Output() stepChangeEvent = new EventEmitter();

  @Input() requireTips: any = [];

  public step: any = "1";

  // 必填项提示信息
  // public requiredTips: any;

  // 获取路由index字段
  public pageIndex: any;

  // 获取路由index字段（内码）
  public nFundNo: any;
  // 几个填写后自动标蓝字段的flag
  // 产品管理联席委员会
  public dLxCommitteeCheckedFlag: any = false;
  // 产品审核会
  public dAuditCommitteeCheckedFlag: any = false;

  // 状态条数据
  public stepBarData: any;

  // 状态条子数据数组
  public subStepCollection = [];

  // 延期募集
  public delay_collection: any;
  constructor(
    public dataService: DataService,
    public stepbarService: StepbarService,
    public publicEventService: PublicEventService,
    private route: ActivatedRoute,
    public router: Router
  ) {
    // 路由切换
    this.route.params.subscribe((data) => {
      this.nFundNo = data.nFundNo;

      this.pageIndex = data.index;
      if (this.pageIndex != 'zh') {
        // 加载状态条
        this.loadStatusTree();
      }
    })
  }
  // 判断是否点击了特殊按钮（需填写日期才标蓝的）如果日期未填写，提示“请填写xx日期”
  isSpecialSubStep(subStep) {
    let that = this
    switch (subStep.sStatus) {
      default: return true;
      case "产品管理联席委员会":
        that.publicEventService.checkNullEmit.emit("产品管理联席委员会");
        break;
      case "产品审核会":
        that.publicEventService.checkNullEmit.emit("产品审核会");
        break;
      case "上报证监会":
        that.publicEventService.checkNullEmit.emit("上报证监会");
        break;
      case "证监会审核":
        that.publicEventService.checkNullEmit.emit("证监会审核");
        break;
      case "证监会批复":
        that.publicEventService.checkNullEmit.emit("证监会批复");
        break;
    }
  }
  // 点击切换子步骤
  changeLabel(subStep) {
    let that = this;
    this.isSpecialSubStep(subStep)
    if (!this.isSpecialSubStep(subStep)) return;
    // 判断是否点击了同一个步骤
    _.forEach(that.stepBarData, function (item, index) {
      _.forEach(item.subTree, function (it, index) {
        if (it.sStatus == subStep.sStatus) {
          if (it.isCheck == 1) {
            setTimeout(() => {
              window['swal']("提示", "该步骤已标记，请不要重复标记", "warning")
            }, 1000)
          } else {
            window['swal']({
              "customClass": "product-detail-sweetalert",
              title: "确认?",
              text: "是否确认切换到  " + subStep.sStatus + '  状态',
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "rgb(30,185,225)",
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              closeOnConfirm: true
            }, function () {
              subStep.isCheck = 1;
              subStep.checkR = 1;
              that.alterStatusTree();
            });
          }
        }
      })
    })
  }
  // 调用修改状态树接口
  alterStatusTree() {
    var that = this;
    // 存放当前已标蓝的父状态
    let parIsChecked = [];
    this.subStepCollection = [];
    _.forEach(this.stepBarData, function (item, index) {
      if (item.isCheck == 1) {
        parIsChecked.push(item.nOrderId);
      }
      _.forEach(item.subTree, function (it, index) {
        if (it.checkR == 1) {
          that.subStepCollection.push(it.sStatusCode);
        }
      })
    })
    let maxParIsChecked = _.max(parIsChecked);
    var maxParIsCheckedIndex = parIsChecked.findIndex(function (value, index, arr) {
      return value == maxParIsChecked;
    });
    var maxParIsCheckedStatusCode = this.stepBarData[maxParIsCheckedIndex].sStatusCode;
    let finalDataCollection = _.uniq(this.subStepCollection);

    var putBody = {
      "nFundNo": this.nFundNo,
      "sStatus": maxParIsCheckedStatusCode,
      "sSubStatus": _.last(finalDataCollection),
      "sSubStatusSets": finalDataCollection
    }
    this.stepbarService.alterTree(putBody).subscribe(data => {
      if (data) {
        var lastParCollection = [];

        _.forEach(this.stepBarData, function (item, index) {
          if (item.isCheck == 1) {
            lastParCollection.push(item.nOrderId);
          }
        })
        var lastParChecked = _.max(lastParCollection);
        // 如果当前状态是“方案设计及立项”，隐藏审核信息的tab
        if (lastParChecked == 1) {
          this.publicEventService.hideInfo.emit('1');
        } else if (lastParChecked == 2) {
          this.publicEventService.hideInfo.emit('2');
        } else {
          this.publicEventService.hideInfo.emit('3');
        }
      }
    })
  }

  // 点击切换父步骤
  changeStep(ParentStep) {
    let that = this;
    // 存放除被点击的父状态以外的其他父状态
    let StepCollection = [];
    // 存放当前已标蓝的父状态
    let parIsChecked = [];

    _.forEach(that.stepBarData, function (item, index) {
      StepCollection.push(item.nOrderId);
      if (item.isCheck == 1) {
        parIsChecked.push(item.nOrderId);
      }
    })

    let maxParIsChecked = _.max(parIsChecked);
    var maxParIsCheckedIndex = parIsChecked.findIndex(function (value, index, arr) {
      return value == maxParIsChecked;
    });

    if (maxParIsChecked >= 4 && ParentStep.nOrderId <= 4) {
      window['swal']("提示", this.stepBarData[maxParIsCheckedIndex].sStatus + "状态不能回退！", "warning")
      return false;
    } else {
      if (Math.abs(ParentStep.nOrderId - maxParIsChecked) === 1) {
        /* 如果新点击的步骤在原来最大的步骤之前，要除去原来最大步骤的颜色 */
        if (maxParIsChecked > ParentStep.nOrderId) {
          window['swal']({
            "customClass": "product-detail-sweetalert",
            title: "确认?",
            text: "请确认是否回退到" + ParentStep.sStatus + '状态？当前子状态将清空标蓝！',
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "rgb(30,185,225)",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: true
          },
            function () {
              that.stepBarData[maxParIsCheckedIndex].isCheck = 0;
              // 回滚时清空上一个步骤的子状态
              _.forEach(that.stepBarData[maxParIsCheckedIndex].subTree, function (item, index) {
                // 如果是这五个特殊输入框，保留标蓝状态
                if (item.sStatus == '产品管理联席委员会' || item.sStatus == '产品审核会' || item.sStatus == '上报证监会' || item.sStatus == '证监会审核' || item.sStatus == '证监会批复') {
                  item.isCheck = item.isCheck;
                }
                // 其他的子状态一律取消标蓝
                else {
                  item.isCheck = 0;
                  item.checkR = 0;
                }
              })
              ParentStep.isCheck = 1;
              that.step = ParentStep.nOrderId;
              that.alterStatusTree();
            });
        }
        else {
          window['swal']({
            "customClass": "product-detail-sweetalert",
            title: "确认?",
            text: "请确认是否切换到" + ParentStep.sStatus + '状态？',
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "rgb(30,185,225)",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: true
          },
            function () {
              if (ParentStep.nOrderId == 3) {
                that.requireInput('3');
                setTimeout(() => {
                  if (that.requireTips.length == 0) {
                    ParentStep.isCheck = 1;
                    that.step = ParentStep.nOrderId;
                    that.alterStatusTree();
                  }
                  else {
                    window['swal']("提示", that.requireTips + '未填写或未保存，不能跳转到' + ParentStep.sStatus + '状态', "warning")
                  }
                }, 500)
              }
              else if (ParentStep.nOrderId == 4) {
                that.requireInput('4');
                setTimeout(() => {
                  if (that.requireTips.length == 0) {
                    ParentStep.isCheck = 1;
                    that.step = ParentStep.nOrderId;
                    that.alterStatusTree();
                  }
                  else {
                    window['swal']("提示", that.requireTips + '未填写或未保存，不能跳转到' + ParentStep.sStatus + '状态', "warning")
                  }
                }, 200)
              }
              else if (ParentStep.nOrderId == 5) {
                that.requireInput('5');
                setTimeout(() => {
                  if (that.requireTips.length == 0) {
                    ParentStep.isCheck = 1;
                    that.step = ParentStep.nOrderId;
                    that.alterStatusTree();
                  }
                  else {
                    window['swal']("提示", that.requireTips + '未填写或未保存，不能跳转到' + ParentStep.sStatus + '状态', "warning")
                  }
                }, 800)
              }
              else {
                ParentStep.isCheck = 1;
                that.step = ParentStep.nOrderId;
                that.alterStatusTree();
              }

            });
        }

      } else {
        // 如果点了相同步骤
        if (ParentStep.nOrderId == maxParIsChecked) {
          window['swal']({
            type: "warning",
            title: "提示",
            text: "当前状态已是" + ParentStep.sStatus + "状态，不需要切换。",
            closeOnConfirm: true,
            showConfirmButton: true
          });
        } else if (ParentStep.nOrderId > maxParIsChecked) {
          // 跳了后面的步骤
          window['swal']({
            type: "warning",
            title: "提示",
            text: "请先切换到" + that.stepBarData[maxParIsCheckedIndex + 1].sStatus + "阶段！",
            closeOnConfirm: true,
            showConfirmButton: true
          });
        }
        else if (ParentStep.nOrderId < maxParIsChecked) {
          // 跳了前面的步骤
          window['swal']({
            type: "warning",
            title: "",
            text: "请先回退到" + that.stepBarData[maxParIsCheckedIndex - 1].sStatus + "阶段！",
            closeOnConfirm: true,
            showConfirmButton: true
          });
        }
      }
    }
  }

  // 判断输入框必填
  requireInput(changeTo) {
    switch (changeTo) {
      // 跳转到已报会在审
      case "3":
        this.stepChangeEvent.emit('3');
        break;
      // 跳转到已获批
      case "4":
        this.stepChangeEvent.emit('4');
        break;
      // 跳转到已发行
      case "5":
        this.stepChangeEvent.emit('5');
        break;
    }
  }
  ngOnInit() {
    let that = this;
    // 初始化子状态集合
    this.subStepCollection = [];
    // 延期募集隐藏控制
    this.delay_collection = this.dataService.delay_collection;
    // 接收发射过来的数据，根据接收值标蓝相应步骤并修改状态树。
    this.publicEventService.eventEmit = new EventEmitter();
    this.publicEventService.eventEmit.subscribe((value: any) => {
      switch (value) {
        // 产品管理联席委员会如果不是空的，子状态标蓝！
        case "dLxCommitteeCheckedFlag":
          this.dLxCommitteeCheckedFlag = true;
          _.forEach(this.stepBarData, function (item, index) {
            _.forEach(item.subTree, function (it, index) {
              if (it.sStatus == '产品管理联席委员会') {
                it.isCheck = 1;
              }
            })
          })
          break;
        // 产品管理联席委员会如果是空的，子状态变灰色才对啊！
        case "dLxCommitteeCheckedFlagNull":
          _.forEach(this.stepBarData, function (item, index) {
            _.forEach(item.subTree, function (it, index) {
              if (it.sStatus == '产品管理联席委员会') {
                it.isCheck = 0;
              }
            })
          })
          break;
        case "dAuditCommitteeCheckedFlag":
          this.dAuditCommitteeCheckedFlag = true;
          _.forEach(this.stepBarData, function (item, index) {
            _.forEach(item.subTree, function (it, index) {
              if (it.sStatus == '产品审核会') {
                it.isCheck = 1;
              }
            })
          })
          break;
        case "dAuditCommitteeCheckedFlagNull":
          _.forEach(this.stepBarData, function (item, index) {
            _.forEach(item.subTree, function (it, index) {
              if (it.sStatus == '产品审核会') {
                it.isCheck = 0;
              }
            })
          })
          break;
        case "dCsrsSbCheckedFlag":
          this.dAuditCommitteeCheckedFlag = true;
          _.forEach(this.stepBarData, function (item, index) {
            _.forEach(item.subTree, function (it, index) {
              if (it.sStatus == '上报证监会') {
                it.isCheck = 1;
              }
            })
          })
          break;
        case "dCsrsSbCheckedFlagNull":
          _.forEach(this.stepBarData, function (item, index) {
            _.forEach(item.subTree, function (it, index) {
              if (it.sStatus == '上报证监会') {
                it.isCheck = 0;
              }
            })
          })
          break;
        case "dCsrsSlCheckedFlag":
          this.dAuditCommitteeCheckedFlag = true;
          _.forEach(this.stepBarData, function (item, index) {
            _.forEach(item.subTree, function (it, index) {
              if (it.sStatus == '证监会审核') {
                it.isCheck = 1;
              }
            })
          })
          break;
        case "dCsrsSlCheckedFlagNull":
          _.forEach(this.stepBarData, function (item, index) {
            _.forEach(item.subTree, function (it, index) {
              if (it.sStatus == '证监会审核') {
                it.isCheck = 0;
              }
            })
          })
          break;
        case "dCsrsReplyCheckedFlag":
          this.dAuditCommitteeCheckedFlag = true;
          _.forEach(this.stepBarData, function (item, index) {
            _.forEach(item.subTree, function (it, index) {
              if (it.sStatus == '证监会批复') {
                it.isCheck = 1;
              }
            })
          })
          break;
        case "dCsrsReplyCheckedFlagNull":
          _.forEach(this.stepBarData, function (item, index) {
            _.forEach(item.subTree, function (it, index) {
              if (it.sStatus == '证监会批复') {
                it.isCheck = 0;
              }
            })
          })
          break;
      }
    })
  }

  public loadStatusTree() {
    let that = this;
    this.stepBarData = [];
    var getBody = {
      "nFundNo": this.nFundNo,
    }
    var lastParCollection = [];
    this.stepbarService.list(getBody).subscribe(data => {
      if (data) {
        _.forEach(data.subTree, function (item, index) {
          if (item.isCheck == 1) {
            lastParCollection.push(item.nOrderId);
          }
          _.forEach(item.subTree, function (it, index) {
            it.checkR = it.isCheck;
          })
        })
        this.stepBarData = data.subTree;
        // 获取当前最后已选中父步骤

        var lastParChecked = _.max(lastParCollection);
        // 如果当前状态是“方案设计及立项”，隐藏审核信息的tab
        if (lastParChecked == 1) {
          this.publicEventService.hideInfo.emit('1');
        } else if (lastParChecked == 2) {
          this.publicEventService.hideInfo.emit('2');
        } else {
          this.publicEventService.hideInfo.emit('3');
        }
        this.step = lastParChecked;
      }
    })
  }

}
